<template>
<view class="container">
    <!-- <view class='tab'>
      <view v-for="(tab, index) in tab" :key="index" :style='"width:"+(100/(tab.length))+"%"' :class="(showTabIndex == index ? 'activeTab':'noneUse')" :data-id="index" @tap="bindTab">{{item.name}}</view>        
    </view> -->

    <swiper class="Tab_page" :current="showTabIndex" :style="'height: ' + (sysHeight) + 'px;'" @change="changeIndex"> 
      <swiper-item v-for="(tab, index) in tab" :key="index">
        <view class="swiperPageContainer">
          <view class="freshView">
            <view class="freshView_text">{{refreshText}}</view>
            <image src="https://image1.sansancloud.com/aikucun/2018_03/16/15/36/57_988.jpg?x-oss-process=style/preview_120"></image>
          </view>
           <scroll-view :style="'height: ' + (sysHeight) + 'px;'" class="tab_page_list" scroll-y upper-threshold="-60" lower-threshold="10" :data-index="index" @scroll="scrollEvent" @scrolltoupper="scrollTopToReflesh" @scrolltolower="scrollBottomToLoadMore">
            
            <view class="tab_page_list_container">
                <block v-if="!tab.List">  
                    <view class="noneList">没有相关订单</view>
                </block>
                <block v-else> 
                    <view class="cartContainer" v-for="(list, i) in tab.List" :key="i">
                       <view class="promotionNameItem" v-if="list.promotionName">
                          <view class="promotionNameLine"></view>
                          <view class="promotionName" :style="'background:' + setting.platformSetting.defaultColor"><text>{{list.promotionName}}</text></view>
                       </view>
                      <view class="cartShopName"> 
                        <view class="storageName" v-if="list.storageName"><text>{{list.storageName}}</text></view>
                        <!-- <text class="vity_tag" wx:if='{{list.storageName}}'>{{list.storageName}}</text> 
                        <text class="vity_tag" wx:if='{{list.promotionName}}'>{{list.promotionName}}</text> -->
                        <block v-if="list.easyStatusStr == '作废'"> 
                          <text class :style="'color:' + setting.platformSetting.defaultColor">已作废</text>
                        </block>
                        <block v-else-if="list.easyStatusStr == '完成'"> 
                          <text class :style="'color:' + setting.platformSetting.defaultColor">交易成功</text>
                        </block>
                        <block v-else-if="list.easyStatusStr == '待评价'"> 
                          <text class :style="'color:' + setting.platformSetting.defaultColor">待完成</text>
                        </block>
                        <block v-else>
                          <text class :style="'color:' + setting.platformSetting.defaultColor">{{list.easyStatusStr}}</text>
                        </block>
                      </view>

                      <view class="cartItems" v-for="(orderItem, index) in list.orderItems" :key="index" :data-orderNo="list.orderNo" @tap="lookMore">
                        <view class="itemCheckbox">
                          <image mode="aspectFill" :src="orderItem.itemIcon + '?x-oss-process=style/preview'"></image>
                        </view>
                        <view class="item_infomation">
                          <view class="item_infomation_name font1">{{orderItem.itemName}}</view>

                          <view class="item_infomation_name2" v-if="!!orderItem.measureCartesianId">{{orderItem.measures}}</view>
                          <view class="item_infomation_nums"> 
                            <text class="flexCenter">x {{orderItem.itemCount}}</text>
                          </view>
                          <view class="item_infomation_money">
                            <view>单价:￥<text class="fontPrice">{{orderItem.itemPrice}}</text></view>
                            <text>订单号:{{list.orderNo}}</text>
                          </view>
                        </view>
                      </view>

                      <view class="butn_container">
                          <view>
                            <view class="orderType">
                               <image class="orderTypeIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/11/14/57/30_666.jpg?x-oss-process=style/preview_120"></image>
                            </view>
                          </view>
                          <text>订单金额￥{{list.goodsAmount - list.youhuiAmount}}</text>
                          <text>（优惠￥{{list.youhuiAmount}}）</text>
                          <text>（运费￥{{list.yunfeiAmount}}）</text>
                      </view>
                      <!-- 订单类型不同，按钮不一样 -->
                      <!-- <view wx:if='{{list.easyStatus == 2}}' class='butn_container2'>
                         <text class='mr80' wx:if="{{list.mendianZiti==1}}">门店自提</text>

                          <text data-order='{{list}}' bindtap='editOrder'>编辑订单</text>
                          <text data-order='{{list}}' bindtap='pay'>立即付款</text>
                          <text data-orderNo='{{list.orderNo}}' data-index='{{index}}' bindtap='delectOrder'>删除订单</text>
                      </view>
                      <view wx:if='{{list.payStatus == 1 && list.orderStatus  == 1}}' class='butn_container2'>
                        <text data-orderNo='{{list.orderNo}}' data-index='{{index}}' bindtap='cancelOrder'>取消订单</text>
                      </view>
                      <view wx:if='{{list.easyStatus == 4}}' class='butn_container2'>
                          <text data-orderNo='{{list.orderNo}}' data-index='{{index}}' bindtap='arriverOrder'>确认收货</text>
                      </view> -->

                      <!-- <view wx:if='{{list.easyStatus == 5}}' class='butn_container2'>
                          <text data-orderNo='{{list.orderNo}}' bindtap='pingjiaOrder'>评价</text>
                      </view> -->

                    </view>
                     <view v-if="tab.state.listEnd" class="dixian"> 我是有底线的 ~</view> 
                </block>
            </view>
          </scroll-view>
        </view>
         
      </swiper-item>
    </swiper>
</view>
</template>

<script>

export default {
  data() {
    return {
      orderList: [],
      reflesh: false,
      showTabIndex: 0,
      sysWidth: 320,
      sysHeight: 568,
      tab: [],
      tabBar:[
        {
          name: '全部',
          getUrl: 'order_pintuan.html',
          params: {
            payStatus: "1",
            orderType: '12',
            page: 1
          },
          state: {
            scrollTop:0,
          },
          List: []
        }
      ],
      refreshText: '下拉刷新',
      opt: {},
      params: {
        payStatus: "1",
        orderType: '12',
        page: 1
      },
      state: {
        scrollTop: 0
      },
      setting: "",
      loginUser: ""
    };
  },

  components: {},
  props: {},
  onLoad: function (options) {
    this.opt = options;
    console.log(options);
    this.setData({
      tab: this.tabBar
    });
    this.dellOpt(options);
  },
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting,
      loginUser: getApp().globalData.loginUser,
      sysWidth: getApp().globalData.sysWidth,
      sysHeight: getApp().globalData.sysHeight
    });
  },
  methods: {
    /* 点击tab */
    bindTab: function (e) {
      var index = e.currentTarget.dataset.id;

      if (this.showTabIndex == index) {
        return;
      }

      this.setData({
        showTabIndex: index
      });
    },

    /* 滑动事件 */
    changeIndex: function (e) {
      var index = e.detail.current;
      let tab = this.tab;
      let focusTab = tab[index];

      if (!focusTab.List || focusTab.List.length == 0) {
        this.getOrderList(focusTab, index, 1);
      }

      this.setData({
        showTabIndex: index
      });
    },

    /* 获取数据 */
    getOrderList: function (focusTab, index, fresh) {
      let params = focusTab.params;
      let tab = this.tab;
      var customIndex = getApp().globalData.AddClientUrl("/get_order_list.html", params);
      var that = this; // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('-----------orderList--------');
          console.log(res.data);
          focusTab.params.pageSize = res.data.pageSize;
          focusTab.params.curPage = res.data.curPage;
          focusTab.params.totalSize = res.data.totalSize;
          let result = res.data.result;

          if (fresh) {
            focusTab.List = [];
          }

          if (!res.data.result || res.data.result.length == 0) {
            focusTab.List = null;
          } else {
            focusTab.List = focusTab.List.concat(result);
          }

          tab[index] = focusTab;
          that.setData({
            tab: tab
          });
          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        },
        complete: function () {
          setTimeout(function () {
            that.loading = false;
          }, 2000);
          that.setData({
            refreshText: '下拉刷新'
          });
        }
      });
    },

    /* 下拉刷新 */
    onPullDownRefresh: function (e) {
      console.log('粗发下拉事件');
      this.setData({
        refreshText: '松开手指即可刷新'
      });
      let index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];

      if (!this.FreshIng) {
        this.FreshIng = true;
      } else {
        return;
      }
    },

    //刷新数据
    freshList(focusTab, index) {
      if (this.FreshIng) {
        this.FreshIng = false;
        console.log('mmmmmmmmmm   加载数据中   mmmmmmm');
        let that = this;
        focusTab.params.page = 1;
        this.getOrderList(focusTab, index, 1);
      }
    },

    scrollEvent: function (e) {
      let index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];

      if (this.FreshIng && e.detail.scrollTop > -10) {
        console.log('mmmmmmmmmm   1   mmmmmmm');
        this.freshList(focusTab, index);
      }
    },

    /* 加载更多 */
    scrollBottomToLoadMore: function (e) {
      let that = this;
      console.log(this.loading);

      if (this.loading) {
        return;
      }

      this.loading = true;
      let index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];

      if (focusTab.params.totalSize > focusTab.params.page * focusTab.params.pageSize) {
        ++focusTab.params.page;
        this.getOrderList(focusTab, index);
      } else {
        console.log('noMore');
        focusTab.state.listEnd = true;
        this.setData({
          tab: tab
        });
      }

      setTimeout(function () {
        that.loading = false;
      }, 2000);
    },

    /* 第一次加载 */
    dellOpt: function (options) {
      if (this.tab.length == 0) {
        return;
      }

      let easyStatus = options.easyStatus;

      if (!easyStatus) {
        easyStatus = 0;
      }

      let tab = this.tab;
      let index = 0;

      for (let i = 0; i < tab.length; i++) {
        if (tab[i].params.easyStatus == easyStatus) {
          index = i;
        }
      }

      if (index == 0) {
        this.getOrderList(tab[index], index);
      }

      this.setData({
        showTabIndex: index
      });
    },

    /* 支付 */
    pay: function (e) {
      var order = e.currentTarget.dataset.order;
      var that = this;
      console.log(order);
      getApp().globalData.payItem = order;
      this.setData({
        reflesh: true
      });
      wx.navigateTo({
        url: '/pages/submit_order_result/index'
      });
    },

    /* 订单详细 */
    lookMore: function (e) {
      var orderNo = e.currentTarget.dataset.orderno;
      console.log(orderNo);
      this.setData({
        reflesh: true
      });
      wx.navigateTo({
        url: '/pages/order_pintuan_detail/index?orderNo=' + orderNo
      });
    },

    /* 编辑订单 */
    editOrder: function (e) {
      var order = e.currentTarget.dataset.order;
      var orderNo = order.orderNo;
      console.log(order);
      this.setData({
        reflesh: true
      });
      console.log("===========tab======", this.tab);
      let list = this.tab;
      let data = null;

      for (let i = 0; i < list.length; i++) {
        //  console.log(list[i])
        for (let j = 0; j < list[i].List.length; j++) {
          //  console.log(list[i].List[j])
          if (orderNo == list[i].List[j].orderNo) {
            data = list[i].List[j];
            console.log("==========data========", data);
          }
        }
      }

      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/edit_order/index?orderNo=' + data.orderNo
        });
      }, 200);
    },

    /* 取消订单 */
    cancelOrder: function (e) {
      var orderNo = e.currentTarget.dataset.orderno;
      var index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];
      var that = this;
      wx.showModal({
        title: '提示',
        content: '取消订单',
        success: function (res) {
          if (res.confirm) {
            let param_post = {};
            param_post.orderNo = orderNo;
            var customIndex = getApp().globalData.AddClientUrl("/cancel_order.html", param_post, 'post');
            wx.request({
              url: customIndex.url,
              data: customIndex.params,
              header: getApp().globalData.headerPost,
              method: 'POST',
              success: function (res) {
                if (res.data.errcode == '0') {
                  console.log(res.data);
                  wx.showToast({
                    title: '取消订单成功',
                    icon: 'success',
                    duration: 1000
                  });
                  setTimeout(function () {
                    focusTab.params.page = 1;
                    that.getOrderList(focusTab, index, 1);
                  }, 1000);
                } else {
                  wx.showToast({
                    title: res.data.errMsg,
                    image: '/images/icons/tip.png',
                    duration: 1000
                  });
                }
              },
              fail: function (res) {
                getApp().globalData.loadFail();
              }
            });
          } else if (res.cancel) {}
        }
      });
    },

    /* 删除订单 */
    delectOrder: function (e) {
      var orderNo = e.currentTarget.dataset.orderno;
      var index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];
      var that = this;
      wx.showModal({
        title: '提示',
        content: '确认删除',
        success: function (res) {
          if (res.confirm) {
            let param_post = {};
            param_post.orderNo = orderNo;
            var customIndex = getApp().globalData.AddClientUrl("/order_unshow.html", param_post, 'post');
            wx.request({
              url: customIndex.url,
              data: customIndex.params,
              header: {
                'content-type': 'application/x-www-form-urlencoded',
                'Cookie': getApp().globalData.cookie
              },
              method: 'POST',
              success: function (res) {
                if (res.data.errcode == '0') {
                  console.log(res.data);
                  wx.showToast({
                    title: '删除成功',
                    icon: 'success',
                    duration: 1000
                  });
                  setTimeout(function () {
                    focusTab.params.page = 1;
                    that.getOrderList(focusTab, index, 1);
                  }, 1000);
                } else {
                  wx.showToast({
                    title: res.data.errMsg,
                    image: '/images/icons/tip.png',
                    duration: 1000
                  });
                }
              },
              fail: function (res) {
                getApp().globalData.loadFail();
              }
            });
          } else if (res.cancel) {}
        }
      });
    },

    /* 订单评价 */
    pingjiaOrder: function (e) {
      var orderNo = e.currentTarget.dataset.orderno;
      this.setData({
        reflesh: true
      });
      wx.navigateTo({
        url: '/pages/order_shop_comment/index?orderNo=' + orderNo
      });
    },

    /* 订单到货 */
    arriverOrder: function (e) {
      var orderNo = e.currentTarget.dataset.orderno;
      var that = this;
      console.log(orderNo);
      wx.showModal({
        title: '提示',
        content: '确认到货',
        success: function (res) {
          if (res.confirm) {
            let param_post = {};
            param_post.orderNo = orderNo;
            var customIndex = getApp().globalData.AddClientUrl("/order_received.html", param_post, 'post');
            wx.request({
              url: customIndex.url,
              data: customIndex.params,
              header: getApp().globalData.headerPost,
              method: 'POST',
              success: function (res) {
                console.log(res.data);

                if (res.data.errcode == '0') {
                  wx.showToast({
                    title: '订单已到货',
                    icon: 'success',
                    duration: 2000
                  });
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/order_list_tab/index'
                    });
                  }, 2000);
                } else {
                  wx.showToast({
                    title: res.data.errMsg,
                    image: '/images/icons/tip.png',
                    duration: 2000
                  });
                }
              },
              fail: function (res) {
                getApp().globalData.loadFail();
              }
            });
          } else if (res.cancel) {}
        }
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style scoped>
@import "./index.css";
</style>